import random
import string

from django.contrib.auth.decorators import login_required
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, reverse
from django.core.mail import send_mail
from .models import *
from django.views.decorators.http import require_http_methods
from .forms import *
from django.contrib.auth import get_user_model, login, logout
from app.models import *
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse


User = get_user_model()

# Create your views here.

@require_http_methods(['GET', 'POST'])      # 指定请求方式只能为get和post
def bllogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):                  # 找到用户并校验密码
                login(request, user)                                    # 做用户的登录
                # 判断用户是否选择了记住我
                if not remember:
                    # 如果没有点击记住我，那么就要设置过期时间为0，即浏览器关闭后就失效
                    request.session.set_expiry(0)
                # 如果点击了，则什么都不做，默认使用两周的过期时间
                return redirect('/')        # 返回首页
            else:
                print("用户名或密码错误！")
                form.add_error('email', '邮箱或者密码错误！')
                return redirect(reverse('blogauthor:login'))
@require_http_methods(['GET', 'POST'])      # 指定请求方式只能为get和post
def register(request):
    if request.method == 'GET':             # get方法
        return render(request, 'register.html')
    else:           # post方法
        form = RegisterForm(request.POST)       # 调用写好的form来讲校验数据
        if form.is_valid():                     # 如果校验通过
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            email = form.cleaned_data.get('email')
            User.objects.create_user(username=username, password=password, email=email)     # 创建用户
            return redirect(reverse('blogauthor:login'))            # 跳转到登录界面
        else:
            print(form.errors)
            # 重新跳转到注册界面
            return render(request, 'register.html', {'errors': form.errors})


# 发送邮箱验证码
def sen_email_captcha(request):
    email = request.GET.get('email')
    print("获取到的email是", email)
    if not email:
        return JsonResponse({'code': 400, 'msg': '邮箱不能为空'})

    # 生成验证码
    captcha = ''.join(random.sample(string.digits, 6))
    print("生成的验证码是", captcha)
    # 存储验证码到数据库
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})       # 没有则新建
    send_mail("注册验证码", message=f"您的注册验证码是{captcha}", recipient_list=[email],
              from_email=None)
    return JsonResponse({'code': 200, 'msg': '邮箱验证码发送成功'})


# 退出登录
def bllogout(request):
    logout(request)
    return redirect('/')

# 发布博客
# @login_required(login_url='blogauthor:login')           # 校验用户是否登录

@require_http_methods(['GET', 'POST'])
@login_required()               # 简写，是因为setting里面已经配置了LOGIN_URL，一劳永逸
def public_blog(request):
    if request.method == 'GET':
        category = BlogCategoryModel.objects.all()
        return render(request, 'public_blog.html', {'categories': category})
    else:
        form = PublishBlogForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            blog = BlogModel.objects.create(title=title, content=content, category=category_id, author=request.user)
            return JsonResponse({"code":200, "msg":"博客发布成功！", "data":{"blog_id":blog.id}})
        else:
            print(form.errors)
            return JsonResponse({"code":400, "msg":"参数错误，博客发布失败！"})


